package wpackage;

class Student extends Thread {
    public void run() {
        synchronized (this) {
            try {
                wait(); // 进入等待状态，等待 teacher 唤醒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("张三开始听课");
        }
    }
}

class Teacher extends Thread {
    private Student student;

    public Teacher(Student student) {
        this.student = student;
    }

    public void run() {
        try {
            Thread.sleep(1000); // 等待一秒以确保 Student 先进入等待状态
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (student) {
            System.out.println("上课！");
            System.out.println("张三正在睡觉，不听课");

            try {
                Thread.sleep(500); // 每次输出后暂停一会
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for (int i = 2; i <= 3; i++) { // 从第二次开始循环上课输出
                System.out.println("上课！");
                try {
                    Thread.sleep(500); // 每次输出后暂停一会
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            student.notify(); // 唤醒 student 线程
            System.out.println("张三被老师叫醒了");
        }
    }
}

